import logging
import openpyxl


class ExcelUtil(object):
    @classmethod
    def get_workbook(cls, file_bytes):
        try:
            data = openpyxl.load_workbook(file_bytes)
            return data
        except Exception as ex:
            logging.info("获取excel对象时，出现异常，原因：%s" % str(ex))
            return None

    @classmethod
    def get_sheets(cls, workbook):
        sheet_names = workbook.sheetnames
        if not sheet_names:
            return None
        sheet_names = sheet_names
        sheet_list = []
        for sheet_name in sheet_names:
            sheet = workbook.get_sheet_by_name(sheet_name)
            sheet_list.append(sheet)
        return sheet_list

    def get_data(self, file_bytes):
        data = self.get_workbook(file_bytes)
        if not data:
            return []

        sheet_list = self.get_sheets(data)
        if not sheet_list:
            return []

        try:
            res_data = []
            for sheet in sheet_list:
                row_num, column_num = sheet.max_row, sheet.max_column

                _res_data = []
                for x in range(1, row_num + 1):
                    item_data = []
                    for y in range(1, column_num + 1):
                        item_data.append((sheet.cell(row=x, column=y)).value)
                    _res_data.append(item_data)
                res_data.append(_res_data)
            return res_data
        except Exception as ex:
            logging.info("解析excel出现异常，原因：%s" % str(ex))
            return []
